<template>
  <div class="online-counter">
    <p>当前在线人数: <span class="count">{{ onlineCount }}</span></p>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';

const onlineCount = ref(0);
const sessionId = ref('');

const fetchOnlineCount = async () => {
  try {
    const response = await fetch('/api/online/count');
    const data = await response.json();
    onlineCount.value = data.count;
  } catch (error) {
    console.error('获取在线人数失败:', error);
  }
};

const enter = async () => {
  try {
    const response = await fetch('/api/online/enter', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      }
    });
    const data = await response.json();
    sessionId.value = data.sessionId;
    console.log('用户已上线，sessionId:', sessionId.value);
    fetchOnlineCount();
  } catch (error) {
    console.error('上线请求失败:', error);
  }
};

const leave = async () => {
  if (!sessionId.value) return;

  try {
    // 使用fetch发送请求，同时监听页面卸载事件
    const controller = new AbortController();
    const signal = controller.signal;

    // 发送下线请求
    await fetch('/api/online/leave', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ sessionId: sessionId.value }),
      signal
    });

    console.log('用户已下线');
  } catch (error) {
    // 如果是页面卸载导致的请求中断，属于正常情况
    if (error.name !== 'AbortError') {
      console.error('下线请求失败:', error);
    }
  }
};

onMounted(() => {
  enter();

  // 定时刷新在线人数
  const intervalId = setInterval(fetchOnlineCount, 5000);

  // 监听页面卸载事件
  const handleBeforeUnload = () => {
    // 使用navigator.sendBeacon作为备选方案
    if (navigator.sendBeacon) {
      navigator.sendBeacon('/api/online/leave', JSON.stringify({ sessionId: sessionId.value }));
    } else {
      // 传统fetch在页面卸载时可能不可靠
      leave();
    }
  };

  window.addEventListener('beforeunload', handleBeforeUnload);

  // 组件卸载时清除定时器和事件监听器
  onBeforeUnload(() => {
    clearInterval(intervalId);
    window.removeEventListener('beforeunload', handleBeforeUnload);
    leave();
  });
});
</script>

<style scoped>
.online-counter {
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  text-align: center;
}

.count {
  font-size: 24px;
  font-weight: bold;
  color: #007bff;
  margin-left: 8px;
}
</style>